package com.cicadasmall.support.sqlbuilder.builder.dml.impl;

import com.cicadasmall.support.sqlbuilder.AbstractSqlBuilder;
import com.cicadasmall.support.sqlbuilder.builder.dml.UpdateDateSqlBuilder;

import java.util.ArrayList;
import java.util.List;


public class MysqlUpdateDataSqlBuilder extends AbstractSqlBuilder<MysqlUpdateDataSqlBuilder> implements UpdateDateSqlBuilder<MysqlUpdateDataSqlBuilder> {

    private final static String UPDATE_DATA_BEGIN = "UPDATE `{table}` SET ";

    @Override
    public MysqlUpdateDataSqlBuilder update(String conditionField, Object conditionValue, List<String> fields, List<Object> paramValues) {
        StringBuilder sqlBody = new StringBuilder();
        for (int i = 0; i < fields.size(); i++) {
            sqlBody.append("`").append(fields.get(i)).append("`= ");
            Object paramValue = paramValues.get(i);
            if (paramValue instanceof String) {
                sqlBody.append("'");
                sqlBody.append(paramValues.get(i));
                sqlBody.append("'");
            } else {
                sqlBody.append(paramValue);
            }
            if (i >= fields.size() - 1) {
                sqlBody.append(" ");
            } else {
                sqlBody.append(",");
            }
        }
        if (conditionValue instanceof String) {
            conditionValue = "'" + conditionValue + "'";
        }
        sqlBody.append(" WHERE ")
                .append("`")
                .append(conditionField)
                .append("`=")
                .append(conditionValue)
                .append(";");
        setSqlBody(sqlBody.toString());
        return this;
    }

    @Override
    public MysqlUpdateDataSqlBuilder tableName(String tableName) {
        clearSql();
        setTableName(tableName);
        setSqlHead(UPDATE_DATA_BEGIN);
        return this;
    }


    public static void main(String arg[]) {
        MysqlUpdateDataSqlBuilder insertDataSqlBuilder = new MysqlUpdateDataSqlBuilder();
        List<String> fields = new ArrayList<>();
        fields.add("attr_class_id");
        fields.add("attr_name");
        fields.add("attr_store_type");
        fields.add("attr_location");
        List<Object> paramValues = new ArrayList<>();
        paramValues.add(1);
        paramValues.add("111");
        paramValues.add(3);
        paramValues.add("400004444");
        paramValues.add(5);

        String sql = insertDataSqlBuilder.tableName("sys_attr").update("id", 1, fields, paramValues).build();

        System.out.println(sql);
    }

    @Override
    public String buildSql() {
        return build();
    }
}
